package com.producer.utility;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.nio.charset.StandardCharsets;

/**
 * 消息转换器，用于将要发送的消息转换成队列需要的格式，以及将从队列中获取的消息转换成程序需要的格式
 */
public class JsonMessageConverter implements MessageConverter {
	private static final ObjectMapper objectMapper = new ObjectMapper();
	static {
		// 在遇到未知属性的时候不抛出异常
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
	}

	/**
	 *
	 * @param object
	 * @param messageProperties
	 * @return
	 * @throws MessageConversionException
	 */
	@Override
	public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
		try {
			return new Message(objectMapper.writeValueAsString(object).getBytes(StandardCharsets.UTF_8), messageProperties);
		}catch(Exception e) {
			return new Message(null, messageProperties);
		}
	}

	@Override
	public Object fromMessage(Message message) throws MessageConversionException {
		try {
			return objectMapper.readValue(message.getBody(), JsonNode.class);
		}catch(Exception e) {
			throw new MessageConversionException("",e);
		}
	}
}
